package com.farewell.blog.service.impl;

import com.farewell.blog.exception.NotFoundExcepiton;
import com.farewell.blog.pojo.User;
import com.farewell.blog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;

/**
 * @author Farewell
 * @date 2021/2/15
 */
@Service
public class MyUserDetailsService implements UserDetailsService {
    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        // 从数据库获取用户对象
        User user = userService.getUserByUserName(s);

        // 判空
        if (null == user) {
            throw new NotFoundExcepiton("用户不存在");
        }

        // 添加权限
        String authority = user.getAuthority();
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority(authority));

        // 返回UserDetail实现类，注意这里是SpringSecurity的user类
        return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), authorities);
    }
}
